<template>
  <div>
    <p-transfer
      :data-source="mockData"
      :target-keys="targetKeys"
      :disabled="disabled"
      :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
      :show-select-all="false"
      @change="onChange"
      @search="handleSearch"
    >
      <template
        slot="children"
        slot-scope="{
          props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
          on: { itemSelectAll, itemSelect },
        }"
      >
        <p-table
          :row-selection="
            getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
          "
          style="max-width:550px;min-width:400px"
          :scroll="tableScroll"
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :data-source="filteredItems"
          size="small"
          :loading="loadingTable"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              on: {
                click: () => {
                  if (itemDisabled || listDisabled) return;
                  itemSelect(key, !selectedKeys.includes(key));
                },
              },
            })
          "
        />
      </template>
    </p-transfer>
  </div>
</template>
<script>
import { HrefJump } from '@/mixins/OnlAutoListMixin'
import difference from 'lodash/difference'
import aTransfer from 'ant-design-vue/lib/transfer'
import { getAction, downFile } from '@/api/manage'
import 'ant-design-vue/dist/antd.css'
export default {
    components: {
        aTransfer
    },
    mixins: [HrefJump],
    props: {
      recode: {
        type: String,
        default: ''
      },
      context: {
        type: String,
        default: ''
      },
      destFields: {
        type: String,
        default: ''
      },
      orgFields: {
        type: String,
        default: ''
      },
      // 是不是table
      isJeTable: {
        type: Boolean,
        default: false
      },
      // add api
      add: {
        type: String,
        default: ''
      },
      // list api
      listaip: {
        type: String,
        default: ''
      },
       // 主表id
      mainTableID: {
        type: Object,
        default: function () {
          return {}
        }
      },
      // 唯一字段
      onlyField: {
        type: String,
        default: ''
      },
       // 唯一字段
      datas: {
        type: Array,
      }

    },
  data () {
    return {
      sorter: {
          column: '',
          order: 'desc',
        },
      table: {
          // 分页参数
          pagination: {
            current: 1,
            pageSize: 10,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          }
        },
      mockData: [],
      targetKeys: [],
      disabled: false,
      showSearch: false,
      leftColumns: [],
      rightColumns: [],
      loadingTable: true,
      arrData: [], // 目标数据
      dataKeys: [], // 目标key
      url: {
        getColumnsAndData: this.context + '/online/cgreport/api/getColumnsAndData/',
        getQueryInfo: this.context + '/online/cgreport/api/getQueryInfo/',
        getParamsInfo: this.context + '/online/cgreport/api/getParamsInfo/'
      },
    }
  },
  computed: {
      tableScroll: function () {
        if (this.leftColumns.length > 6) {
          return { x: this.leftColumns.length * 120 + 40 }
        }
      }
    },
  mounted () {
      // this.getCoLumns()
      if (this.isJeTable) {
        this.getTableList(this.datas)
      } else {
        this.getList()
      }
 },
  methods: {
    clearvisible(){
      this.loadingTable = true
    },
    handleSearch (dir, value) {
      console.log('search:', dir, value)
    },
    toHump (name) {
        return name.replace(/\_(\w)/g, function (all, letter) {
          return letter.toUpperCase()
        })
      },
      // table Popup
      // getTableList
    getTableList (data) {
      const that = this
      this.mockData = []
      this.leftColumns = []
      this.rightColumns = []
      this.targetKeys = []
      this.dataKeys = []
      this.arrData = [] // 唯一字段值
      data.forEach((item, index) => {
        that.arrData.push(item[this.onlyField])
      })
      getAction(`${this.url.getColumnsAndData}${this.recode}`, { 'pageSize': 30 }).then(res => {
        if (res.success) {
          const newArr = []
            const filternewArr = [] // 用来转换的  过滤后的
            const filterArr = [] // 用来存储新的数组
            res.data.data.records.forEach((item, index) => {
              for (const i in item) {
                if (!this.orgFields.split(',').includes(i)) {
                  delete item[i]
                }
              }
              filternewArr.push(this.sort(item))
            })

            res.data.data.records.forEach((element, index) => {
                element['key'] = index.toString()
                element['title'] = index.toString()
                element['disabled'] = false
                newArr.push(element)
            })
            filternewArr.forEach((element, index) => {
                element['key'] = index.toString()
                element['title'] = index.toString()
                element['disabled'] = false
                filterArr.push(element)
            })
            const filterKey = filterArr.filter(item => {
              if (that.arrData.includes(item[this.onlyField])) {
                return true
              }
            })
            filterKey.forEach((elm, indexm) => {
              this.targetKeys.push(elm.key)
              this.dataKeys.push(elm.key)
            })
            this.loadingTable = false
            const columns = []
            res.data.columns.forEach(item => {
              columns.push(item)
            })
            this.rightColumns.push(res.data.columns[0])
            this.rightColumns = columns
            this.mockData = newArr
            this.leftColumns = columns
        } else {
          this.$message.warning(res.msg)
        }
      }).catch(res => {
            that.loading = false
            that.$message.warning(res)
        })
    },
    getList () {
      const that = this
      const list = this.listaip
      const pagesize = { 'limit': 30 }
      const mainTableID = this.mainTableID
       const param = Object.assign(mainTableID, pagesize)
      const promise = new Promise(function (resolve, reject) {
        getAction(list, param).then(res => {
          if (res.success) {
             resolve(res.data.records)
          } else {
            reject(res.message)
          }
        })
      })
      promise.then((data) => {
        this.mockData = []
        this.leftColumns = []
        this.rightColumns = []
        this.targetKeys = []
        this.dataKeys = []
        this.arrData = [] // 唯一字段值
        data.forEach((item, index) => {
          that.arrData.push(item[this.onlyField])
        })
        getAction(`${this.url.getColumnsAndData}${this.recode}`, { 'pageSize': 30 }).then(res => {
          if (res.success) {
            const newArr = []
            const filternewArr = [] // 用来转换的  过滤后的
            const filterArr = [] // 用来存储新的数组
            res.data.data.records.forEach((item, index) => {
              for (const i in item) {
                if (!this.orgFields.split(',').includes(i)) {
                  delete item[i]
                }
              }
              filternewArr.push(this.sort(item))
            })

            res.data.data.records.forEach((element, index) => {
                element['key'] = index.toString()
                element['title'] = index.toString()
                element['disabled'] = false
                newArr.push(element)
            })
            filternewArr.forEach((element, index) => {
                element['key'] = index.toString()
                element['title'] = index.toString()
                element['disabled'] = false
                filterArr.push(element)
            })
            const filterKey = filterArr.filter(item => {
              if (that.arrData.includes(item[this.onlyField])) {
                return true
              }
            })
            filterKey.forEach((elm, indexm) => {
              this.targetKeys.push(elm.key)
              this.dataKeys.push(elm.key)
            })
            this.loadingTable = false
            this.rightColumns.push(res.data.columns[0])
            this.mockData = newArr
            this.leftColumns = res.data.columns
            this.table.pagination.total = Number(res.data.data.total)
          } else {
            this.$message.warning(res.msg)
          }
        })
      }).catch(res => {
            that.loading = false
            that.$message.warning(res)
        })
    },
    // 转换
    sort (obj) {
         var objs = {}
         const arr = this.orgFields.split(',')
         arr.forEach((items, indexs) => {
           for (var i in obj) {
              if (i == items) {
                objs[i] = obj[i]
              }
          };
         })
          const newSelectionRows = []
          const param = {} // 新生成一个新的数组出来,来保存需要过滤的数据
          var keyMap = {}
          this.destFields.split(',').forEach((item, index) => {
            newSelectionRows.push(this.toHump(item))
          })
          arr.forEach((item, index) => {
            if (objs[item] != undefined) {
              param[item] = objs[item].toString()
            }
            keyMap[item] = newSelectionRows[index]
          })
          for (var key in param) {
            var newKey = keyMap[key]
            if (newKey) {
              if (param[newKey] !== param[key]) {
                param[newKey] = param[key]
                delete param[key]
              }
            }
          }
         return param
      },
    getCoLumns () {
          this.mockData = []
          this.leftColumns = []
          this.rightColumns = []
          this.targetKeys = []
        getAction(`${this.url.getColumnsAndData}${this.recode}`).then(res => {
          if (res.success) {
            const newArr = []
            res.data.data.records.forEach((element, index) => {
                element['key'] = index.toString()
                element['title'] = index.toString()
                element['disabled'] = false
                newArr.push(element)
            })
            this.loadingTable = false
            this.rightColumns = res.data.columns
            this.mockData = newArr
            this.leftColumns = res.data.columns
          } else {
            this.$message.warning(res.msg)
          }
        })
    },
    onChange (nextTargetKeys, pagination, filters) {
      console.log(nextTargetKeys)
      console.log(pagination)
      console.log(filters)
      this.targetKeys = nextTargetKeys
    },

    triggerDisable (disabled) {
      this.disabled = disabled
    },

    triggerShowSearch (showSearch) {
      this.showSearch = showSearch
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    },
  },
}
</script>
